<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改审读样本')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-sample-detail" th:object="${rvSample}">
        <input name="id" th:field="*{id}" type="hidden">

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">样本名称：</label>
                    <div class="col-sm-8">
                        <input type="text" name="name" th:field="*{name}" class="form-control" placeholder="" required>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">样本介质：</label>
                    <div class="col-sm-8">
                        <!--                        <input type="text" name="medium" class="form-control" placeholder="请输入文本">-->
                        <select name="medium" th:with="type=${@dict.getType('review_sample_medium')}"
                                class="selectpicker" data-none-selected-text="请选择" required>
                            <option value="">--请选择--</option>
                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                    th:value="${dict.dictValue}" th:field="*{medium}"></option>
                        </select>

                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">出版单位：</label>
                    <div class="col-sm-8">
<!--                        type="hidden"-->
                        <input  type="hidden"  name="publisherId" th:field="*{publisherId}" class="form-control" placeholder="" readonly required>
                        <input type="text" id="publisher" name="publisher" th:field="*{publisher}" class="form-control" placeholder="" required>
                        <span class="help-block m-b-none"><i class="fa fa-info-circle"></i>输入出版单位名称，自动补全</span>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">出版期刊：</label>
                    <div id="element" class="col-sm-8">
                        <div class="form-group">
                            <div class="col-sm-5">
                                <select name="journalSuper" class="type form-control "
                                        th:attr="data-value=${rvSample.journalSuper}" data-first-title="请选择" required>
                                    <option value="">请选择</option>
                                </select>
                            </div>
                            <div class="col-sm-7">
                                <select name="journalSub" class="router form-control "
                                        th:attr="data-value=*{journalSub}" data-first-title="请选择" required>
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">缴送时间：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="deliveryTime" th:value="${#dates.format(rvSample.deliveryTime, 'yyyy-MM-dd')}"
                                   class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">出版标识：</label>
                    <div class="col-sm-8">
                        <input name="identification" th:field="*{identification}" class="form-control"
                               placeholder="ISBN 邮发代号 内刊号" type="text" required>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label ">样本封面：</label>
                    <div class="col-sm-10">
                        <!--   type="hidden" -->
                        <input type="hidden" th:field="*{cover}" name="cover" readonly required>
                        <div class="file-loading">
                            <input class="form-control file-upload" id="cover" name="file" type="file">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label">其它说明：</label>
                    <div class="col-sm-10">
                        <textarea name="sampleDesc" maxlength="500" class="form-control" placeholder="输入说明文字内容"
                                  th:field="*{sampleDesc}" rows="4"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: bootstrap-select-js"/>
<th:block th:include="include :: jquery-cxselect-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: bootstrap-typeahead-js"/>
<script th:inline="javascript">
    var prefix = ctx + "publish/sample";

    var handle=null;
    $(document).ready(function () {

        handle = setInterval(function () {
            $('.help-block').remove();
            $('input.form-control').attr('readonly', true);
            $('textarea.form-control').attr('readonly', true);
            $('select[name="journalSuper"],select[name="journalSub"],select[name="medium"]').attr("readonly",true).attr('disabled',true);
            $('input[name="deliveryTime"]').attr('disabled',true);
            $('.file-actions button[title="删除文件"]').remove();
            $('.btn-file').remove();
            $('.file-caption-main').remove();
            $('button.close').remove();
            if ($('input.form-control').attr('readonly')) {
                clearInterval(handle);
            }
        }, 800);

    });


    $("#form-sample-detail").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            $.operate.save(prefix + "/edit", $('#form-sample-detail').serialize());
        }
    }

    $("input[name='deliveryTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    var data = [
        {   //图书
            "s": [

            ],
            "v": "图书",
            "n": "图书"
        },
        {   //日报、周报、半月报、月报、双月报
            "s": [
                {"s": null, "v": "日报", "n": "日报"},
                {"s": null, "v": "周报", "n": "周报"},
                {"s": null, "v": "半月报", "n": "半月报"},
                {"s": null, "v": "月报", "n": "月报"},
                {"s": null, "v": "双月报", "n": "双月报"},
            ],
            "v": "公开报",
            "n": "公开报"
        },
        {   //周刊、旬刊、半月刊、月刊、双月刊、季刊
            "s": [
                {"s": null, "v": "周刊", "n": "周刊"},
                {"s": null, "v": "旬刊", "n": "旬刊"},
                {"s": null, "v": "半月刊", "n": "半月刊"},
                {"s": null, "v": "月刊", "n": "月刊"},
                {"s": null, "v": "双月刊", "n": "双月刊"},
                {"s": null, "v": "季刊", "n": "季刊"}
            ],
            "v": "期刊",
            "n": "期刊"
        },
        {   //日报、周一到周五、周二四六、周一三五、周二四、周二五、周二四五、周三六
            "s": [
                {"s": null, "v": "日报", "n": "日报"},
                {"s": null, "v": "周一到周五", "n": "周一到周五"},
                {"s": null, "v": "周二四六", "n": "周二四六"},
                {"s": null, "v": "周一三五", "n": "周一三五"},
                {"s": null, "v": "周二四", "n": "周二四"},
                {"s": null, "v": "周二五", "n": "周二五"},
                {"s": null, "v": "周二四五", "n": "周二四五"},
                {"s": null, "v": "周三六", "n": "周三六"}
            ],
            "v": "区县报",
            "n": "区县报"
        },
        {   //半月刊、月刊、双月刊、季刊
            "s": [
                {"s": null, "v": "半月刊", "n": "半月刊"},
                {"s": null, "v": "月刊", "n": "月刊"},
                {"s": null, "v": "双月刊", "n": "双月刊"},
                {"s": null, "v": "季刊", "n": "季刊"},
            ],
            "v": "内部资料",
            "n": "内部资料"
        }
    ];
    $('#element').cxSelect({
        selects: ['type', 'router'],
        jsonValue: 'v',
        data: data
    });
    var sca = function (event) {
        $("input[name='" + event.currentTarget.id + "']").val("");
        sca = function () {
        }
    }

    $(".file-upload").each(function (i) {
        var vals = new Array()
        var preList = new Array();
        if ($.common.isNotEmpty($("input[name='" + this.id + "']").val())) {
            var str = $("input[name='" + this.id + "']").val();
            var strs = new Array();
            strs = str.split(",");
            for (i = 0; i < strs.length; i++) {
                vals[i] = ctx.slice(0, ctx.length - 1) + strs[i];
            }

        }
        var previewJson = preList;
        var preConfigList = new Array();
        for ( var i = 0; i < vals.length; i++) {
            var array_element = vals[i];
            var name=vals[i].substring(vals[i].lastIndexOf("/")+1);
            var tjson = {
                caption: name, // 展示的文件名
                width: '100px',
                alt:array_element,
                extra: {id: 100}
            };
            preConfigList[i] = tjson;
        }
        $(this).fileinput({
            uploadUrl: '/common/upload',
            initialPreviewAsData: true,
            initialPreview: vals,
            maxFileCount: 0,
            showUpload: false,
            showRemove: true,
            maxFileSize: 30000,
            autoReplace: true,
            //allowedFileExtensions: ['jpg', 'png', 'bmp', 'jpeg'],
            showUpload: false, //是否显示上传按钮
            showCaption: true,//是否显示标题
            browseClass: "btn btn-primary hide",//按钮样式
            dropZoneTitle: " ",
            otherActionButtons:'<button type="button" class="kv-file-down btn btn-sm btn-default" {dataKey} title="下载附件"><i class="fa fa-cloud-download"></i></button>',
            layoutTemplates: {
                actionDelete: '', //去除上传预览的缩略图中的删除图标
                actionUpload: '',//去除上传预览缩略图中的上传图片图标；
                //     actionZoom:''   //去除上传预览缩略图中的查看详情预览的缩略图标。
            },
            previewFileIcon: '<i class="fa fa-file-o text-info"></i>',
            preferIconicPreview: true,// 是否优先显示图标  false 即优先显示图片
            previewFileIconSettings: {
                'docx': '<i class="fa fa-file-word-o text-primary"></i>',
                'doc': '<i class="fa fa-file-word-o text-primary"></i>',
                'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'ppt': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
                'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
                'sql': '<i class="fa fa-file-word-o text-primary"></i>',
                'txt': '<i class="fa fa-file-text-o text-info"></i>',
                'rtf': '<i class="fa fa-file-text-o text-info"></i>',
            },
            initialPreviewConfig: preConfigList
        }).on('filebatchselected', function (event, data, id, index) {
            $(this).fileinput("upload");
        }).on('fileuploaded', function (event, data, previewId, index) {
            //若重新上传文件，清空当前文件路径,只执行一次清空函数
            sca(event);
            if ($("input[name='" + event.currentTarget.id + "']").val() == "") {
                $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName);
            } else {
                $("input[name='" + event.currentTarget.id + "']").val($("input[name='" + event.currentTarget.id + "']").val() + ',' + data.response.fileName);
            }
        }).on('filecleared', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        }).on('filesuccessremove', function (event, id, index) {
            var fileUrlList = $("input[name='" + event.currentTarget.id + "']").val().split(",");
            fileUrlList.splice(index, 1);
            $("input[name='" + event.currentTarget.id + "']").val(fileUrlList);
        }).on('filedeleted', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        }).on('filepreremove', function (event, id, index) {
            var str_after = index.split('_')[1];
            var fileUrlList = $("input[name='" + event.currentTarget.id + "']").val().split(",");
            fileUrlList.splice(str_after, 1);
            $("input[name='" + event.currentTarget.id + "']").val(fileUrlList);
        });
        // $(this).fileinput('_initFileActions');
    });


    /**
     * 其他按钮（如下载）绑定时间
     */
    $(document).on('click', '.kv-file-down', function (e, id, index) {
        var download = "";
        // 获取父级DIV
        var fileIndex = $(this).parents(".file-preview-frame").attr("data-fileindex");

        var fileValue = $(this).parents(".col-sm-10").children("input").val();
        if (fileIndex) {
            var number = fileIndex.match(/\d/);
            if (number) {
                download = fileValue.split(",")[number];
            }
        }
        var name=download.substring(download.lastIndexOf("/")+1);
        if(download!=""){
            downloadFile(download,name);
        }
    });

    function downloadFile(url,name){
        var a = document.createElement("a");
        a.download = name;
        a.href = url;
        $("body").append(a); // 修复firefox中无法触发click
        a.click();
        $(a).remove();
    };

    function downloadIamge(imgsrc, name) {//下载图片地址和图片名
        let image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function() {
            let canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            let context = canvas.getContext("2d");
            context.drawImage(image, 0, 0, image.width, image.height);
            let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
            let a = document.createElement("a"); // 生成一个a元素
            let event = new MouseEvent("click"); // 创建一个单击事件
            a.download = name || "photo"; // 设置图片名称
            a.href = url; // 将生成的URL设置为a.href属性
            a.dispatchEvent(event); // 触发a的单击事件
        };
        image.src = imgsrc;
    }
    // 部门补全
    $("#publisher").typeahead({
        source: function (query, process) {
            return $.ajax({
                url: '/publish/unit/list',
                type: 'post',
                data: {companyName: query, pageSize: 10, pageNum: 1, isAsc: 'asc', orderByColumn:''},
                success: function (result) {
                    var items =[];
                    var resultList = result.rows.map(function (item) {
                        var aItem = {id: item.id, name: item.companyName};
                        items.push(aItem);
                    });
                    return process(items);
                }
            });
        },
        afterSelect: function (item) {//选中一条数据后的回调函数，此处可以向隐藏域赋值数据id
            console.log(item);//取出选中项的值
            $("input[name='publisherId']").val(item.id);
        },
        delay: 800,
        fitToElement: true
    });



</script>
</body>
</html>